package byj.com.meishi.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.IOException;
import java.util.List;

import byj.com.meishi.R;
import byj.com.meishi.adapter.RecyclerAdapter;
import byj.com.meishi.bean.Movie;
import byj.com.meishi.utils.AnalysisJson;
import byj.com.meishi.utils.OkHttpClientUtils;


/**
 * A simple {@link Fragment} subclass.
 */
public class TitleFragment extends Fragment {
    private String path;
    private int page;
    private RecyclerView recyclerView;
    private Handler mHandler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                list = (List<Movie>) msg.obj;
                adapter = new RecyclerAdapter(list,getActivity());
                recyclerView.setAdapter(adapter);
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    };
    private List<Movie> list;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerAdapter adapter;

    public TitleFragment() {
        // Required empty public constructor
    }
    public void setPath(String path,int page){
        this.path=path;
        this.page=page;
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_title, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiprefresh_item);
        assert  recyclerView!=null;
        final GridLayoutManager manager = new GridLayoutManager(view.getContext(),2);
        recyclerView.setLayoutManager(manager);
        downloadJsondata(page);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light,android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        downloadJsondata(page);
                    }
                },3000);

            }
        });

     recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
         boolean isSlidingToLast = false;
         @Override
         public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
             super.onScrollStateChanged(recyclerView, newState);


             int lastVisibleItemPosition = manager.findLastCompletelyVisibleItemPosition();
             int total=manager.getItemCount();

             if (newState ==RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition + 1 ==manager.getItemCount()) {
                 if(lastVisibleItemPosition==(total-1)&&isSlidingToLast){
                     downloadJsondata1(++page);
                 }

             }
         }

         @Override
         public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
             super.onScrolled(recyclerView, dx, dy);
           if(dy>0){
               //大于0表示，正在向下滑动
               isSlidingToLast=true;
           }else {
               //小于等于0表示停止或向上滚动
               isSlidingToLast=false;
           }
         }
     });





    }

    private void downloadJsondata(int page) {
        pinjiepath(path,page);
        new  Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String categoryJson = OkHttpClientUtils.getStringFromUrl(path);
                    List<Movie> movies = AnalysisJson.analysisRecyclerItemData(categoryJson);
                    Message obtain = Message.obtain();
                    obtain.what=1;
                    obtain.obj=movies;
                    mHandler.sendMessage(obtain);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void downloadJsondata1(int page) {
        final String pinjiepath = pinjiepath(path, page);
        new  Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String categoryJson = OkHttpClientUtils.getStringFromUrl(pinjiepath);
                    List<Movie> movies = AnalysisJson.analysisRecyclerItemData(categoryJson);
                   list.addAll(movies);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private String pinjiepath(String path,int count){
        path=path+"&&+page="+count;
        return path;
    }
}
